
import dayjs from 'dayjs';
import { notification } from "ant-design-vue";
import { nextTick } from 'vue';

export const webToUeMessige = (name: string, val: any) => { // ue4消息
  if (window.emitUIInteraction) { // 像素流
    window.emitUIInteraction({ event: name, data: val });
    console.log('发送至UE像素流消息：', name, val);
  } else { // webUI
    try {
      window.ue4(name, val);
      console.log('发送至UE消息:', name, val);
    } catch (error) {
      notification.error({
        message: "发送消息到UE失败！",
        description: `
          浏览器平台和版本:${navigator.appVersion},\n 是否开启cookie:${navigator.cookieEnabled},
          \n 操作系统平台:${navigator.platform},\n User-agent头部值:${navigator.userAgent}
        `,
      });
    }
  }
};

export const getDuration = (
  start: string | number | Date,
  end: string | number | Date
): string => {
  const startDate = dayjs(start);
  const endDate = dayjs(end);
  const diff = endDate.diff(startDate); // 获取时间差的毫秒数
  // 计算天数
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));
  const remainingTime = diff % (1000 * 60 * 60 * 24);
  // 计算小时数
  const hours = Math.floor(remainingTime / (1000 * 60 * 60));

  return `${days}天${hours}小时`;
};

export const randomColor = () => { // 随机颜色
  return '#' + Math.floor(Math.random() * 0xffffff).toString(16);
};

export const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); // 延迟


export const getUUID = () => {
  return 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxyxxxxxxx'.replace(/[xy]/g, (c: string) => {
    // @ts-ignore 如果是x则生成一个0-15之间的随机数并转换为十六进制表示；如果是y则生成一个特定的十六进制数
    return (c === 'x' ? (Math.random() * 16) | 0 : 'r&0x3' | '0x8').toString(16);
  });
};

export const titleCase = (str: string) => { // 首字母大小
  return str.replace(/( |^)[a-z]/g, L => L.toUpperCase());
};

export const camelCase = (str: string) => { // 下划转驼峰
  return str.replace(/_[a-z]/g, str1 => str1.substr(-1).toUpperCase());
};

export const random = (min: number, max: number = 0) => { // 生成随机整数
  let temp = null;
  if (min > max) { // 如果传入的最小值大于最大值，则交换两者的值
    temp = min;
    min = max;
    max = temp;
  }
  return Math.floor(Math.random() * (max - min + 1)) + min;
};


export const nclickEvent = (num: number, dom: HTMLElement, fn: Function) => {
  dom.removeEventListener('dblclick', () => { });
  const n = num < 1 ? 1 : num;
  let count = 0;
  let lastTime = 0; // 用于记录上次结束的时间
  const handler = (event: any) => {
    const currentTime = new Date().getTime(); // 获取本次点击的时间
    count = (currentTime - lastTime) < 300 ? count + 1 : 0; // 如果本次点击的时间和上次结束时间相比大于300毫秒就把count置0
    lastTime = new Date().getTime();
    if (count >= n - 1) {
      fn(event, n);
      count = 0;
    }
  };
  dom.addEventListener('click', handler);
};


export const loading = {
  show: (string = '正在加载页面 &nbsp; 稍等片刻 &nbsp; 精彩马上回来！', rmDom: HTMLElement) => {
    rmDom && rmDom.parentNode?.removeChild(rmDom);
    const bodys: Element = document.body;
    const div = document.createElement('div');
    div.className = 'loader-wrapper';
    div.innerHTML = `
          <div class="loader"></div>
          <div class="loader-section section-left"></div>
          <div class="loader-section section-right"></div>
          <div class="load_title">
            <p style="fontSize:3.2vw;">${string}</p>
          </div>
        `;
    bodys.insertBefore(div, bodys.childNodes[0]);
  },
  hide: () => {
    nextTick().then(() => {
      const el = document.querySelector('.loader-wrapper');
      el && el.parentNode?.removeChild(el);
    });
  }
};

// 两个对象数组取交集
export const  findIntersection = (arr1:any, arr2:any) =>{
  // 将数组中的对象转换为字符串以便比较
  const stringify = (obj:any) => JSON.stringify(obj);
  
  // 将 arr2 转换为 Map，便于查找
  const map = new Map(arr2.map((obj:any) => [stringify(obj), obj]));
  
  // 用于存储交集的数组
  const intersection = [] as any[];
  
  // 遍历 arr1
  arr1.forEach((obj:any) => {
    const key = stringify(obj);
    // 如果 arr2 中存在相同对象，则加入交集数组
    if (map.has(key)) {
      intersection.push(obj);
    }
  });
  
  return intersection;
}

// 两个对象数组取交集(根据unionName筛选，看情况修改)
export const unionById = (array1:any, array2:any, unionName:string) => {
  // 创建一个映射来存储已经遇到的id和对应的对象
  const map = new Map();

  // 遍历第一个数组，将对象添加到映射中
  for (const obj of array1) {
      map.set(obj[unionName], obj);
  }

  // 遍历第二个数组，如果对象的id在映射中不存在，则添加到映射中
  for (const obj of array2) {
      if (!map.has(obj.id)) {
          map.set(obj[unionName], obj);
      }
  }

  // 将映射中的值转换回数组
  return map.values();
}

// 测试compareArrays
// let arr1 = [1,2,3,4,5,"name","jjjjj"]
// let arr2 = [1,3,4,"jjjjj"]
// console.log(compareArrays(arr1,arr2))
export const compareArrays = (arr1: any, arr2: any) => { // 两数组对比
  let missing: { value: any; key: number; }[] = [];
  let added: { value: any; key: number; }[] = [];
  // 检查 list1 中的元素是否在 list2 中存在
  arr1.forEach((item: any, index: number) => {
    if (!arr2.includes(item)) {
      added.push({ value: item, key: index });
    }
  });

  // 检查 list2 中的元素是否在 list1 中存在
  arr2.forEach((item: any, index: number) => {
    if (!arr1.includes(item)) {
      missing.push({ value: item, key: index });
    }
  });
  return { missing, added };
};
